# coding=utf-8
import pygal
import requests
from pygal.style import LightColorizedStyle, LightStyle

url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)

# 将API响应存储在一个变量中
response_dict = r.json()
# 处理结果
print('Total respositorie:', response_dict['total_count'])
repo_dicts = response_dict['items']
print('Repositories returned:', len(repo_dicts))

'''查看一个仓库的items信息字典,打印出JSON里的key,value'''
# repo_dict = repo_dicts[0]
# print("\nkeys:", len(repo_dict))  # 每一个仓库有多少条信息
# for key,value in repo_dict.items():#遍历字典
#     print(str(key)+':'+str(value))
names = []
stars = []
plot_dicts = []

'''for循环查看所有仓库的items信息字典,打印出JSON里的key,value'''
for repo_dict in repo_dicts:
    name = repo_dict['name']
    count = repo_dict['stargazers_count']
    print('\nName:', name)  # 仓库名称
    print('Owner:', repo_dict['owner']['login'])  # 用户
    print('Stars:', count)
    link_html = repo_dict['html_url']
    print('Repository:', link_html)  # 仓库主页
    discription = repo_dict['description']

    print('Description:', discription)  # 描述
    names.append(name)
    stars.append(count)
    plot_dict = {
        'value': count,
        'description': discription,
        'xlink': link_html
    }
    plot_dicts.append(plot_dict)
# 可视化
my_conig = pygal.Config()
my_conig.x_label_rotation = 45
my_conig.show_legend = False  # 不显示Y轴上的图例
my_conig.title_font_size = 24
my_conig.label_font_size = 14  # 副.标题，X轴和Y轴上数值字体的大小
my_conig.major_label_font_size = 18  # 主标题文字的大小，5000的整数倍
my_conig.truncate_label = 15  # x_label超过15个字符时略掉
my_conig.show_guides = True  # 隐藏水平线
my_conig.width = 1000  # 每一个柱状的宽度

chart = pygal.Bar(my_conig);
chart.x_labels = names
chart.title = 'Most-Starred python project on GitHub'

#chart.add('', stars)#传递Y轴数据
chart.add('', plot_dicts)#传递一个字典，就可以给柱状图添加工具提示了，提示描述
chart.render_to_file('python_repos.svg')
